# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# DTCloud v3.0
# QQ:35350428
# 邮件:35350428@qq.com
# 手机：13584935775
# 作者：'sugar'
# 公司网址： www.dtcloud360.com
# Copyright 中亿丰数字科技集团有限公司 2012-2023 Amos
# 日期：2023-05-05
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
import logging
from dtcloud import http
from dtcloud.osv import expression
from dtcloud.addons.rest_controller.handlers import RestController
from ..serializer.user import UserBodyModel


logger = logging.getLogger(__name__)


class UserController(RestController):
    _model = 'res.users'
    _method_map = {
        'list': 'GET',
        'create': 'POST',
        'update': 'PUT',
        'destroy': 'DELETE',
    }
    _default_auth = 'token'
    _prefix = "/api"
    _type = 'jsonify'
    _fields = ('id', 'name', 'dep_id', 'mobile', 'email', 'role_ids', 'status', 'login', 'share', 'sex',
               'introduction', 'real_name')
    # _kwargs = {"permit": True}
    _sex_map = {
        '男': '1',
        '女': '0'
    }

    def create(self, **data):
        """用户创建"""
        data = UserBodyModel(**data).dict(exclude_none=True)
        if http.request.env['res.users'].sudo().search([('login', '=', data['login'])], count=True):
            return self.make_response(None, msg="此账号已存在!", status=-1)
        if not data['password']:
            data['password'] = 'Zyf@123456'
        data['real_name'] = data['name']
        data['groups_id'] = 1

        return super().create(**data)

    def list(self, **query_params):
        if not http.request.env.user.superuser:
            query_params['domains'] = [('id', '>', 7)]
        else:
            query_params['domains'] = [('id', '>=', 2), ('id', 'not in', [6, 7])]

        if "real_name" in query_params:
            name = query_params.pop('real_name')
            domains = expression.OR([[('name', 'ilike', name)], [('real_name', 'ilike', name)]])
            query_params['domains'] = expression.AND([query_params['domains'], domains])

        res, count = self.home_public_list(**query_params)
        for r in res:
            r['sex'] = self._sex_map[r['sex']] if r['sex'] in self._sex_map else r['sex']
            r['role_ids'], _ = self.home_public_list(
                [('status', '=', True), ('id', 'in', [i['id'] for i in r['role_ids']])],
                field_list=('id', 'name'), model="dt.role") if r['role_ids'] else (r['role_ids'], None)

        return self.make_response({
            "total": count,
            "items": res
        })

    def update(self, req_id, **json_data):
        if 'status' in json_data and len(json_data) == 1:
            pass
        else:
            json_data = UserBodyModel(**json_data).dict(exclude_unset=True, exclude_none=True)
            json_data.pop('password', None)
            json_data.pop('login', None)
            json_data['real_name'] = json_data.pop('name')

        return super().update(req_id, **json_data)

    @http.route("/api/res_users/options", auth='token', methods=['GET'], type="jsonify")
    def options(self, name=None, dept_id=None, role_code=None, status=None):
        domains = [('share', '=', False), ('id', '>', 6)]
        if name:
            domains.append(('real_name', 'ilike', name))
        if dept_id:
            domains.append(('dep_id', '=', int(dept_id)))
        if role_code:
            domains.append(('role_ids.code', '=', role_code))
        if status is not None:
            if status in ('1', 1, 'true'):
                domains.append(('status', '=', True))
            else:
                domains.append(('status', '=', False))
        users, _ = self.home_public_list(domains, field_list=('id', 'dep_id', 'status', 'real_name',
                                                              'mobile', 'email'), limit=10000)
        return self.make_response(users)

    @http.route("/api/res_users/password", auth='token', methods=['PUT'], type="jsonify", permit=True)
    def reset_password(self, **kwargs):
        user_id = kwargs.pop('user_id', None)
        if not user_id:
            return self.make_response(None, status=-1, msg='参数缺失!')

        password = 'Zyf@123456'
        user = http.request.env[self._model].sudo().browse(int(user_id))
        res = user.write({
            "password": password
        })

        return self.make_response(res)
